<!--
 * @Descripttion: 参与询价
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-10-17 13:54
 * @LastEditors: a12
 * @LastEditTime: 2020-10-17 13:54
-->
<template>
  <div>
    <div class="page-box">
      <el-row class="base-box" :gutter="20">
        <el-col :span="12">
          <h3 class="box-title">项目基本信息</h3>
          <el-form class="base-box-info" label-width="160px" :label-position="labelPosition" size="mini"
                   label-suffix=":">
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="项目名称">{{baseInfo.projectName}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目编号">{{baseInfo.projectNo}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目状态">{{baseInfo.projectStateName}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托状态" style="color: blue; font-size: 24px;">{{baseInfo.orderStateStr}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总预算(元)" class="budget">{{baseInfo.sumBudgetStr}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="询价开始时间">{{baseInfo.startTime|formeTime}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="询价结束时间">{{baseInfo.endTime|formeTime}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托说明">{{baseInfo.orderRemark}}</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最多报价次数">{{baseInfo.bidNumber}}</el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="交货期">{{baseInfo.requireDate|formeTime}}至{{baseInfo.requireEndDate|formeTime}}</el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="送货地点">{{baseInfo.requireAddress}}</el-form-item>
              </el-col>
              <el-col v-if="baseInfo.projectState === '00026_5'">
                <el-form-item label="询价失败原因">{{baseInfo.invalidRemark}}</el-form-item>
              </el-col>
            </el-row>
            <el-col v-for="(item, index) in rulesInfo" :key="index">
              <el-form-item :label="item.controlName">{{item.detailName}}</el-form-item>
            </el-col>
          </el-form>
        </el-col>
        <el-col :span="12" class="base-box-bid">
          <h2 class="base-box-bid-time">
            <!--  项目倒计时 -->
            <span>
              <i class="el-icon-time base-box-bid-time-icon"></i>
              <!--  倒计时、正在询价  -->
              距离结束时间：{{['00026_0','00026_1'].includes(baseInfo.projectState) ? strCountdown : '已结束'}}
            </span>
             已报名次数：{{number}} / {{baseInfo.bidNumber}} 次</h2>
          <p class="box-title base-box-bid-title">报价排名<span class="base-box-bid-hint">（报价时间以商城系统时间为准，请供应商及时刷新页面，建议供应商尽早完成报价）</span></p>
          <div class="base-box-bid-list">
            <el-table border :data="rankingList" max-height="260px" tyle="width: 100%">
              <el-table-column label="排名" width="50" prop="rowNum"></el-table-column>
              <el-table-column label="供应商" width="140">
                <template slot-scope="scope">
                  <el-popover placement="top" trigger="hover">
                    <div class="cell-content">{{scope.row.suppChinaName}}</div>
                    <p class="overflow" slot="reference">{{scope.row.suppChinaName}}</p>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="总价(元)" prop="sumPriceStr"></el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <!-- 询价列表 -->
      <div>
        <h3 class="box-title">询价列表</h3>
        <div class="base-box-bid-list">
          <el-table border style="width: 100%" :data="demandList" max-height="280px">
            <el-table-column type="expand" width="80">
              <template slot-scope="scope">
                <el-form class="demo-table-expand" :model="scope.row" label-width="80px" label-position="right" label-suffix=":">
                  <el-form-item label="备注说明" style="text-align: left">{{scope.row.remark}}</el-form-item>
                  <el-form-item label="附件">
                    <template>
                      <el-button type="text" @click="clickHandlePreview(scope.row.demandDocument)">{{scope.row.demandDocument|formatFile}}</el-button>
                    </template>
                  </el-form-item>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="单价" prop="editorPrice">
                        <el-input-number v-model="scope.row.editorPrice" :step="1" :precision="2" :min="0.00" :max="999999999.00"></el-input-number>
<!--                        <el-input v-model="props.row.editorPrice" placeholder="请输入单价"-->
<!--                                  @keyup.native="props.row.editorPrice=props.row.editorPrice.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"></el-input>-->
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="人民币总">{{ totalPrice(scope.row)}}</el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goodsName"></el-table-column>
            <el-table-column label="总预算(元)" prop="budgetStr"></el-table-column>
            <el-table-column label="单价预算(元)" prop="priceStr"></el-table-column>
            <el-table-column label="数量" prop="buyNum"></el-table-column>
            <el-table-column label="单位" prop="unit"></el-table-column>
<!--            <el-table-column label="规格" prop="specification"></el-table-column>-->
            <el-table-column label="型号" prop="typeNo"></el-table-column>
<!--            <el-table-column label="标准" prop="qualityStandard"></el-table-column>-->
          </el-table>
          <p class="base-box-bid-total">总价合计：<span class="base-box-bid-total-num">{{goodsTotal}}</span> (元)</p>
        </div>
      </div>
      <!--  联系人信息   -->
      <div class="submit-info">
        <h3 class="box-title">联系人信息</h3>
        <el-form class="submit-info-form" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人名称" prop="biddingLinkman">
                <el-input v-model="ruleForm.biddingLinkman" placeholder="请输入联系人名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人手机" prop="biddingLinkmanMobile">
                <el-input v-model="ruleForm.biddingLinkmanMobile" placeholder="请输入联系人手机"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注说明" prop="remark">
            <el-input v-model="ruleForm.remark"
                      placeholder="请输入备注说明"
                      type="textarea"
                      maxlength="1000"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="fkFileId">
            <el-upload
                :action=fileUrl
                :data="{ fileType: 19}"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                :headers=fileHeaders
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
              <el-button size="small" type="primary">选择附件</el-button>
              <div slot="tip" class="el-upload__tip" style="padding-top: 10px;">最多可以上传1张图片，每张图片大小不能超过5M,支持bmp,png,jpeg格式文件</div>
            </el-upload>
            <el-input v-model="ruleForm.fkFileId" style="display: none"></el-input>
          </el-form-item>
          <el-form-item class="submit-info-btns">
            <el-button type="success" @click="submit('ruleForm')">提交报价</el-button>
<!--            <el-button type="warning" @click="resetForm('ruleForm')">退出本次报价</el-button>-->
          </el-form-item>
        </el-form>
      </div>
      <!-- 查看附件   -->
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {queryDictionaryList,deleteFile,getFileInfo} from '@/api/common.api'
  import {queryProOrderInfo,
    getBiddingRules,
    querySecondTime,
    pageQueryProBiddingList,
    supBidBiddingQueryList,
    doSaveBidBidding,
    doRevokeBidbidding,
    bidBiddingHistoryQueryCount,getProGoodsByOrderId} from '@/api/supplier.api'

  import moment from 'moment'
  // 上传文件
  import {beforeUpload} from '@/util/common'
  // 上传文件
  import fileUpdata from '@/api/file.config'
  export default {
    inject:['reload'], //注入刷新依赖
    name: 'join-bid',
    components: {},
    data() {
      return {
        // 附件
        fileHeaders: fileUpdata.headers(),
        fileUrl: fileUpdata.url,
        dialogVisible:false,
        dialogImageUrl:'',
        fileList:[],

        timer:'', // 定时器
        countdown: 0, // 倒计时
        strCountdown:'', //倒计时显示文字

        labelPosition:'right',
        number: 0,
        ruleForm: {
          biddingLinkman: '',
          biddingLinkmanMobile:'',
          remark:'',
          fkFileId:''
        },
        rules: {
          biddingLinkman: [
            { required: true, message: '请输入联系人名称', trigger: 'blur' }
          ],
          biddingLinkmanMobile: [
            { required: true, message: '请输入联系人手机', trigger: 'blur' },
            { pattern: /(^1(3|4|5|6|7|8|9)\d{9}$)/, message: '手机号格式不正确', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '请输入备注说明', trigger: 'blur' }
          ],
          fkFileId: [
            { required: true, message: '请上传附件', trigger: 'change' }
          ]
        },
        projectId:'',
        stateList:[],
        baseInfo:{},
        rulesInfo:[],
        rankingList:[],
        demandList:[],
        isf: true
      }
    },
    watch: {
      countdown (value) {
        // 清空定时器，并且刷新页面
        if (value === 0 && this.timer) {
          window.clearInterval(this.timer) //清除定时器
          this.timer = ''
          this.reload()
        }
      }
    },
    computed: {
      // 计算总价
      totalPrice() {
        return function (row) {
          const total = Number(row.editorPrice) * 1000 * Number(row.buyNum) / 1000
          return total.toFixed(2)
        }
      },
      // 修改报价总计
      goodsTotal (){
        let total = 0
        for (let i = 0,max = this.demandList.length; i < max; i++) {
          const item = this.demandList[i]
          total= total + Number(item.editorPrice) * 1000 * Number(item.buyNum) / 1000
        }
        return total.toFixed(2)
      }
    },
    filters: {
      formeTime(val){
        return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ' '
      },
      formatFile(value) {
        if (value !== null && value !== undefined && value) {
          const objItem = JSON.parse(value)
          return objItem.name
        } else {
          return ''
        }
      }
    },
    created() {},
    mounted() {
      this.projectId = this.$route.query.projectId
      // 查询询价次数
      this.bidBiddingHistoryQueryCountFn()
      // 查询项目状态
      this.queryProjectStatusListFn()
      // 查询供应商项目个人询价记录
      this.supBidBiddingQueryListFn()
      // 项目基本信息
      this.queryProOrderInfoFn()
      // 查询项目询价规则
      this.getBiddingRulesFn()
      // 项目询价排名列表
      this.pageQueryProBiddingListFn()
    },
    methods: {
      /**
       * @description 查询询价次数
       * @author 穆宏宇
       * @date 2020-11-03 11:44:48
       * @param
       * @return
       * */
      bidBiddingHistoryQueryCountFn () {
        bidBiddingHistoryQueryCount(this.projectId).then(res=>{
          this.number = res
        })
      },
      /**
       * @description 查询项目状态
       * @author 穆宏宇
       * @date 2020-10-13 10:19:10
       * @param
       * @return
       * */
      queryProjectStatusListFn () {
        const param = {dictionaryType: 'project_status'}
        queryDictionaryList(param).then(res=>{
          this.stateList = res
        })
      },
      /**
       * @description 查询供应商项目个人询价记录
       * @author 穆宏宇
       * @date 2020-10-25 17:56:53
       * @param
       * @return
       * */
      supBidBiddingQueryListFn () {
        supBidBiddingQueryList({fkProProjectsId: this.projectId}).then(res=>{
          if (res.length > 0) {
            const curItem = res[0]
            this.$set(this.ruleForm,'biddingLinkman',curItem.biddingLinkman)
            this.$set(this.ruleForm,'biddingLinkmanMobile',curItem.biddingLinkmanMobile)
          }
        })
      },
      /**
       * @description 查询订单详情列表
       * @author 穆宏宇
       * @date 2020-10-20 09:10:11
       * @param
       * @return
       * */
      getdetailsByOrderIdFn(orderId) {
        getProGoodsByOrderId(orderId).then(res=>{
          this.demandList = []
          for (let i = 0, max = res.length; i < max; i++) {
            const item = res[i]
            item['editorPrice'] = 0.00
            this.demandList.push(item)
          }
        })
      },
      /**
       * @description 项目询价排名列表
       * @author 穆宏宇
       * @date 2020-10-25 15:41:59
       * @param
       * @return
       * */
      pageQueryProBiddingListFn (){
        pageQueryProBiddingList({projectId:this.projectId,current:1,size:99999999}).then(res=>{
          this.rankingList = res.records
        })
      },
      // 提交报价
      submit (formName) {
        // 遍历询价列表，检查供应商报价是否填写
        let goodsName = ''
        for (let i = 0, max = this.demandList.length; i < max; i++) {
          const item = this.demandList[i]
          if (Number(item.editorPrice) <= 0){
            goodsName = item.goodsName
            break
          }
        }

        if (goodsName) {
          this.$message({
            message: `询价列表，商品 ${goodsName}, 单价不能为0！`,
            type: 'warning'
          })
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const bidBiddingPriceList = []
            for (let i = 0, max = this.demandList.length; i< max; i++) {
              const item = this.demandList[i]
              bidBiddingPriceList.push({orderDetailId:item.id, price:item.editorPrice})
            }
            const data = {
              bidBiddingPriceList:bidBiddingPriceList,
              fkProProjectsId: this.projectId
            }
            doSaveBidBidding({...data,...this.ruleForm}).then(()=>{
              this.$router.go(-1)
            })
          }
        })
      },
      // 退出
      resetForm(formName) {
        doRevokeBidbidding(this.projectId).then(()=>{
          this.$refs[formName].resetFields();
          this.$router.go(-1)
        })
      },
      // 预览附件
      handlePreview (file) {
        // 获取附件信息
        getFileInfo(file.fileType,file.id).then(res=>{
          if (['image/png','image/jpeg'].includes(res.contextType)) {
            this.dialogImageUrl = res.url
            this.dialogVisible = true
          } else {
            // 下载
            document.location.href = res.url
          }
        })
      },
      // 删除附件
      handleRemove (file, fileList) {

        if (file && file.status === "success") {
          
            this.fileList = this.fileList.filter(item=>item.id !== file.id)
            this.ruleForm.fkFileId = ''
        }
      },
      handleExceed(files, fileList) {
        this.$message.warning(`最多可上传 1 个附件，您已超限`)
      },
      handleAvatarSuccess(res, file) {
        const curFile = {
          name: res.data.submittedFileName,
          url:res.data.url,
          id:res.data.id,
          fileType:res.data.fileType
        }
        this.ruleForm.fkFileId = res.data.id
        this.fileList.push(curFile)

      },
      handleAvatarError(res, file) {
        this.$message.error("文件上传失败，请重试")
      },
      beforeAvatarUpload(file) {
        //const isJPG = file.type === 'image/jpeg';
        const typeList = ['png', 'jpg','jpeg']
        const isJPG = beforeUpload(file,typeList)
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isJPG) {
          this.$message.error('上传文件格式不符合!')
        }
        if (!isLt5M) {
          this.$message.error('上传附件大小不能超过 5MB!')
        }
        return isJPG && isLt5M;
      },
      /**
       * @description 项目基本信息
       * @author 穆宏宇
       * @date 2020-10-14 14:46:35
       * @param
       * @return
       * */
      queryProOrderInfoFn (){
        queryProOrderInfo(this.projectId).then(res=>{
          this.baseInfo = res
          // 项目状态code转文字
          for (let item in this.stateList) {
            if (this.baseInfo.projectState === this.stateList[item].dictionaryKey1) {
              this.baseInfo['projectStateName'] = this.stateList[item].optional1
              break
            }
          }
          // 项目倒计时/正在询价
          if (['00026_0','00026_1'].includes(res.projectState)) {
            // 查询项目距离报名时间
            this.querySecondTimeFn()
          }
          // 查询订单详情列表
          this.getdetailsByOrderIdFn(res.fkEntrustsId)
        })
      },
      /**
       * @description 查询项目询价规则
       * @author 穆宏宇
       * @date 2020-10-14 15:04:02
       * @param
       * @return
       * */
      getBiddingRulesFn () {
        getBiddingRules(this.projectId).then(res=>{
          this.rulesInfo = res
        })
      },
      /**
       * @description 查询项目距离报名时间
       * @author 穆宏宇
       * @date 2020-10-15 13:10:21
       * @param
       * @return
       * */
      querySecondTimeFn () {
        const self = this
        querySecondTime({endTime:this.baseInfo.endTime}).then(res=>{
          self.countdown = res
          self.timer = window.setInterval(() => {
            if (self.countdown >= 0 ) {
              self.countdownFn(self.countdown)
            } else {
              window.clearInterval(self.timer) //清除定时器
            }
          } ,1000)
        })
      },
      // 倒计时执行方法
      countdownFn(second){
        this.countdown= this.countdown - 1
        this.strCountdown = this.$tools.timeStamp(second)
      },
      // 预览附件
      clickHandlePreview (value) {
        if (value !== null && value !== undefined && value) {
          let objItem = ''
          if(value instanceof Object) {
            objItem = value
          } else {
            objItem = JSON.parse(value)
          }
          // 获取附件信息
          getFileInfo(objItem.fileType,objItem.id).then(res=>{
            if (['image/png','image/jpeg'].includes(res.contextType)) {
              this.dialogImageUrl = res.url
              this.dialogVisible = true
            } else {
              // 下载
              document.location.href = res.url
            }
          })
        }
      }
    },
    beforeDestroy () {
      if (this.timer) {
        // window.clearInterval(this.timer) //清除定时器
        this.timer = null
      }
    }
  }
</script>

<style scoped lang="scss">
$red: #ff5438;
$border-line: 2px solid cornflowerblue;
.page-box {
  padding: 20px;
  background-color: white;
}
.box-title {
  border-bottom: $border-line;
}
.base-box {
  &-info {
    padding-top: 10px;
    .budget {
      color: $red;
      font-size: 18px;
    }
  }
  &-bid {
    &-title {
      margin-top: 10px;
    }
    &-time {
      padding: 10px;
      border: $border-line;
      color: $red;
      &-icon {
        color: black;
        font-weight: bold;
      }
    }
    &-hint {
      color: $red;
    }
    &-list {
      padding: 10px;
    }
    &-total {
      padding: 10px 20px;
      margin-bottom: 20px;
      text-align: right;
      border-left: 2px solid goldenrod;
      background: gold;
      &-num {
        color: $red;
        font-size: 18px;
      }
    }
  }
}

.submit-info {
  &-form{
    padding-top: 20px;
  }
  &-btns {
    text-align: center;
  }
}
.demo-table-expand {
 ::v-deep .el-form-item__content {
    text-align: left;
  }
}
.cell-content {
  width: 200px;
  min-height: 20px;
  max-height: 200px;
  overflow-y: auto;
}
.overflow {
  width: 118px;
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
  overflow: hidden;
}

::v-deep .el-icon-arrow-right:before {
  content: "\e6e0";
  font-size: 22px;
  line-height: 10px;
}
// 将el-table的展开图标替换为其他图标
::v-deep .el-table__expand-icon{
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}

::v-deep .el-table__expand-icon
::v-deep .el-icon-arrow-right:before{
  content: "\e6d9";
  border: 1px solid #ccc;
  padding: 2px;
}

::v-deep .el-table__expand-icon--expanded
::v-deep .el-icon-arrow-right:before{
  content: "\e6d8";
}
::v-deep .el-table__expand-icon > .el-icon {
  position: absolute;
  left: 36%;
  top: 70%;
  margin-left: -5px;
  margin-top: -5px;
}
::v-deep .el-table--border td .cell {
  height: 30px;
}
</style>
